package com.xhxi.photobooker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhxi.photobooker.controller.AdminController;
import com.xhxi.photobooker.dto.UserLoginDTO;
import com.xhxi.photobooker.dto.PasswordDTO;
import com.xhxi.photobooker.entity.User;
import com.xhxi.photobooker.mapper.UserMapper;
import com.xhxi.photobooker.properties.WeChatProperties;
import com.xhxi.photobooker.result.Result;
import com.xhxi.photobooker.service.AdminService;
import com.xhxi.photobooker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    public static final String wx_LOGIN ="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private AdminService adminService;

    @Override
    public User saveUser(User user) {
        // 注册用户时，用MD5加密密码
        String encryptedPwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPwd);
        userMapper.insert(user);
        return user;
    }

    @Override
    public User findUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.getByUsername(username);
    }

    @Override
    public List<User> findAllUsers() {
        return userMapper.selectList(null);
    }


    public boolean updateUser(User user) {
        // 不允许通过此接口更新密码
        user.setPassword(null);
        int result = userMapper.updateById(user);
        return result > 0;
    }

    @Override
    public void deleteUser(Long id) {

    }

    @Override
    public User selectByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(queryWrapper);
        //没查找到用户就抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("未找到该用户");
        }
        return user;
    }


    public void startOrStop(Integer status, Long id){

        User user = User.builder()
                .status(status)
                .id(id)
                .build();
        userMapper.updateById(user);

    }

    @Override
    public User Login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //判断用户是否存在
        User user = userMapper.getByUsername(username);
        //不存在
        if (user == null ){
            throw new UserLoginException("用户不存在");
        }
        // 用MD5校验密码
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!user.getPassword().equals(encryptedPwd)) {
            throw new UserLoginException("密码错误");
        }
        return user;
    }
    /*批量修改*/
    @Override
    public Result<Boolean> updateUsers(List<User> userList) {
        try {
            for (User user : userList) {
                if (user.getId() != null) {
                    // 只有当 password 不为空时才加密和更新
                    if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
                        if(adminService.getById(user.getId())){
                            adminService.updatePassword(user);
                        }else {
                            System.out.println("该用户不是管理员");
                        }
                        userMapper.updateUser(user);
                    } else {
                        System.out.println("传递密码为空，不修改密码"); // 不更新密码
                    }
                    userMapper.updateUser(user);
                    System.out.println("debug++++++++++=");
                }
            }
            return Result.success(true);
        } catch (Exception e) {
            // 记录异常日志，返回失败结果
            return Result.error("系统异常，更新失败：" + e.getMessage());
        }
    }


    /*public String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openId
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(wx_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);//将json字符串解析为jsonObject对象
        String openid = jsonObject.getString("openid");

        return openid;
    }*/

    // 自定义业务异常（需创建该类），替代 RuntimeException，便于统一异常处理
    class UserLoginException extends RuntimeException {
        public UserLoginException(String message) {
            super(message);
        }
    }

    @Override
    public boolean changePassword(PasswordDTO passwordDTO) {
        // 1. 校验用户是否存在
        User user = userMapper.selectById(passwordDTO.getUserId());
        if (user == null) {
            // 在实际应用中，可以抛出更明确的异常
            return false;
        }
        // 2. 验证旧密码是否正确
        String encryptedOldPwd = DigestUtils.md5DigestAsHex(passwordDTO.getOldPassword().getBytes());
        if (!user.getPassword().equals(encryptedOldPwd)) {
            // 旧密码不匹配
            return false;
        }
        // 3. 更新为新密码
        String encryptedNewPwd = DigestUtils.md5DigestAsHex(passwordDTO.getNewPassword().getBytes());
        user.setPassword(encryptedNewPwd);
        int result = userMapper.updateById(user);
        return result > 0;
    }
}
